package com.hsc.db.tools;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.hsc.account.oneActivity;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.widget.ListView;
import android.widget.Toast;


public class EmailService {

	public static  Store store;
	public static  Folder folder;

	private static  Message[] message;


	private EmailService(){

	}

	public static  Message[] GetMessage(String host, String name, String pwd)
	{
//		if(message==null)
//		{
		try{
			Properties props = new Properties();
			props.setProperty("mail.imap.partialfetch", "false");
			Session session = Session.getDefaultInstance(props);
			// 取得pop3协议的邮件服务器
			store = session.getStore("pop3");


			// 连接pop.qq.com邮件服务器
			store.connect(host, name, pwd);
			// 返回文件夹对象
			folder = store.getFolder("INBOX");
			// 设置仅读
			folder.open(Folder.READ_WRITE);

			// 获取信息
//					Message[] messageTMP= folder.getMessages();

//					message = new Message[messageTMP.length];
//					int j=0;
//					for(int i=messageTMP.length-1;i>=0;i--)
//					{
//						message[j++]=messageTMP[i];
//					}

//			        return message;
			return folder.getMessages();


		}catch(Exception e)
		{
			e.printStackTrace();
		}
//		}

//		 return message;
		return null;
	}

	public static  void GetMessageToDb(AccountService accs,String host, String name, String pwd,Context context)
	{
		ReciveOneMail pmm;
		try{
			Properties props = new Properties();
			props.setProperty("mail.imap.partialfetch", "false");
			Session session = Session.getDefaultInstance(props);
			// 取得pop3协议的邮件服务器
			store = session.getStore("pop3");


			// 连接pop.qq.com邮件服务器
			store.connect(host, name, pwd);
			// 返回文件夹对象
			folder = store.getFolder("INBOX");
			// 设置仅读
			folder.open(Folder.READ_WRITE);

			// 获取信息
			Message[] messageTMP= folder.getMessages();

			Toast.makeText(context, messageTMP.length, Toast.LENGTH_SHORT).show();

			int j=0;
			for(int i=messageTMP.length-1;i>=0;i--)
			{
				Toast.makeText(context, i, Toast.LENGTH_SHORT).show();

				pmm = new ReciveOneMail((MimeMessage) messageTMP[i]);
//						/* 处理邮件正文 */
				pmm.getMailContent((Part)  messageTMP[i], context);

				MimeMessage mm = (MimeMessage) messageTMP[i];
				try {
					mm.setFlag(Flags.Flag.DELETED, true);
				} catch (MessagingException e) {
					e.printStackTrace();
				}

				if(pmm.getSubject().equals("<data>"))
				{
//							String text = acc.getDate()+","+acc.getAmt()+","+acc.getBalance()+","+acc.getType()+","+acc.getTime();
					String val = pmm.getBodyText();
					String[] data = val.split(",");
					AccountList acc = new AccountList();
					acc.setDate(data[0]);
					acc.setAmt(Double.parseDouble(data[1]));
					acc.setBalance(Double.parseDouble(data[2]));
					acc.setType(data[3]);
					acc.setTime(data[4]);

					accs.save(acc);

				}

			}

			folder.close(true);

		}catch(Exception e)
		{
			e.printStackTrace();
		}


	}


	public static  Folder GetFolder(String host, String name, String pwd)
	{
//		if(folder==null)
//		{
		try{
			Properties props = new Properties();
			props.setProperty("mail.imap.partialfetch", "false");
			Session session = Session.getDefaultInstance(props);
			// 取得pop3协议的邮件服务器
			store = session.getStore("pop3");


			// 连接pop.qq.com邮件服务器
			store.connect(host, name, pwd);
			// 返回文件夹对象
			folder = store.getFolder("INBOX");
			// 设置仅读
			folder.open(Folder.READ_WRITE);



			return folder;


		}catch(Exception e)
		{
			e.printStackTrace();
		}
//		}

		return folder;
	}

	public static void sendTypes(List<useitem> types,ItemService items)
	{
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com");// 存储发送邮件服务器的信息
		props.put("mail.smtp.auth", "false");// 同时通过验证
		props.put("mail.smtp.port", "25");

		Session session = Session.getDefaultInstance(props);

		MimeMessage message = new MimeMessage(session);

		ItemList item1=items.getlDataFlag("1");
		ItemList item2=items.getlDataFlag("2");
		ItemList item3=items.getlDataFlag("3");


		if(item1 == null || item2 == null || item3 == null)
		{
			return;
		}

		// 发件地址
		try{
			javax.mail.Address fromAddress = null;
			fromAddress = new javax.mail.internet.InternetAddress(item1.getType());
			message.setFrom(fromAddress);

			// 收件地址
			javax.mail.Address toAddress = null;
			String tostr = item3.getType();
			if(tostr.indexOf(",")>0)
			{
				String[] to = tostr.split(",");

				for(int i=0;i<to.length;i++)
				{
					if(i==0)
					{
						toAddress = new javax.mail.internet.InternetAddress(to[0]);
						message.addRecipient(Message.RecipientType.TO, toAddress);
					}else
					{
						toAddress = new javax.mail.internet.InternetAddress(to[i]);
						message.addRecipient(Message.RecipientType.CC, toAddress);
					}
				}
			}else
			{
				toAddress = new javax.mail.internet.InternetAddress(tostr);
				message.addRecipient(Message.RecipientType.TO, toAddress);
			}

			/*抄送给自己用于校验邮件是否发送成功*/
			toAddress = new javax.mail.internet.InternetAddress(item1.getType());
			message.addRecipient(Message.RecipientType.CC, toAddress);


			message.setSubject("<item>");

			if(types.size()>0)
			{

				String str="";
				for(int i=0;i<types.size();i++)
				{
					useitem type = types.get(i);
					str = str+ type.getUsetype()+","+type.getFlag()+"|";
				}

				message.setText(str);

				javax.mail.Transport transport = null;
				transport = session.getTransport("smtp");
				transport.connect("smtp.163.com", item1.getType(), item2.getType());

				transport.sendMessage(message, message.getAllRecipients());
				transport.close();
				System.out.println("邮件发送成功！");

			}


		}catch (Exception e) {

			String str="";
			for(int i=0;i<types.size();i++)
			{
				useitem type = types.get(i);
				str = str+ type.getUsetype()+","+type.getFlag()+"|";
			}


			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

			oneActivity.log(df.format(new Date())+"=====邮件发送失败======\n+"+e.getMessage()+"\n=====================\n"+str+"\n======================\n");

		}

	}

	public static void sendMail(List<AccountList> accs,ItemService items,AccountService accService)
	{
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com");// 存储发送邮件服务器的信息
		props.put("mail.smtp.auth", "false");// 同时通过验证
		props.put("mail.smtp.port", "25");

		Session session = Session.getDefaultInstance(props);

		MimeMessage message = new MimeMessage(session);

		ItemList item1=items.getlDataFlag("1");
		ItemList item2=items.getlDataFlag("2");
		ItemList item3=items.getlDataFlag("3");


		if(item1 == null || item2 == null || item3 == null)
		{
			return;
		}

		// 发件地址
		try{
			javax.mail.Address fromAddress = null;
			fromAddress = new javax.mail.internet.InternetAddress(item1.getType());
			message.setFrom(fromAddress);

			// 收件地址
			javax.mail.Address toAddress = null;
			String tostr = item3.getType();
			if(tostr.indexOf(",")>0)
			{
				String[] to = tostr.split(",");

				for(int i=0;i<to.length;i++)
				{
					if(i==0)
					{
						toAddress = new javax.mail.internet.InternetAddress(to[0]);
						message.addRecipient(Message.RecipientType.TO, toAddress);
					}else
					{
						toAddress = new javax.mail.internet.InternetAddress(to[i]);
						message.addRecipient(Message.RecipientType.CC, toAddress);
					}
				}
			}else
			{
				toAddress = new javax.mail.internet.InternetAddress(tostr);
				message.addRecipient(Message.RecipientType.TO, toAddress);
			}

			/*抄送给自己用于校验邮件是否发送成功*/
			toAddress = new javax.mail.internet.InternetAddress(item1.getType());
			message.addRecipient(Message.RecipientType.CC, toAddress);


			message.setSubject("<data>");

			if(accs.size()>0)
			{

				String str="";
				for(int i=0;i<accs.size();i++)
				{
					AccountList acc = accs.get(i);
					str = str+ acc.getDate()+","+acc.getAmt()+","+3+","+
							acc.getType()+","+acc.getTime()+","+acc.getId()+","
							+acc.getRemark()+","+acc.getUse()+"|";
				}

				message.setText(str);

				javax.mail.Transport transport = null;
				transport = session.getTransport("smtp");
				transport.connect("smtp.163.com", item1.getType(), item2.getType());

				transport.sendMessage(message, message.getAllRecipients());
				transport.close();
				System.out.println("邮件发送成功！");


//				for(int i=0;i<accs.size();i++)
//				{
//					AccountList item = accs.get(i);
//					if(item.getId()==0)
//					{
//						accService.delBalance(item);
//					}else
//					{
//						accService.updateBalance(item, 3);
//					}
//
//				}

			}


		}catch (Exception e) {


//			for(int i=0;i<accs.size();i++)
//			{
//				AccountList item = accs.get(i);
//
//				accService.updateBalance(item, item.getId());
//			}


			String str="";
			for(int i=0;i<accs.size();i++)
			{
				AccountList acc = accs.get(i);
				str = str+ acc.getDate()+","+acc.getAmt()+","+3+","+
						acc.getType()+","+acc.getTime()+","+acc.getId()+","+acc.getRemark()+","+acc.getUse()+"|";

			}

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

			oneActivity.log(df.format(new Date())+"=====邮件发送失败======\n+"+e.getMessage()+"\n=====================\n"+str+"\n======================\n");

		}

	}


	public static void freeMassage()
	{
		try{
			if(folder!=null)
			{
				folder.close(true);
			}
			if(store!=null)
			{
				store.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}

	}

}
